package base

import (
	"context"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/errcode"
	basePb "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/base"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/service/base/menu"
	"git.myscrm.cn/golang/stark/v4"
)

type MenuServer struct {
	menuService menu.MenuServiceIface
}

// NewMenuServer 构造展示
func NewMenuServer(menuService menu.MenuServiceIface) basePb.BaseMenuServiceServer {
	return &MenuServer{
		menuService: menuService,
	}
}

// MenuList 菜单列表
func (s *MenuServer) MenuList(ctx context.Context, req *basePb.MenuListRequest) (*basePb.MenuListResponse, error) {
	var response = &basePb.MenuListResponse{}
	menuConfigList, err := s.menuService.MenuConfig(ctx, req.GetOnlyCurrentUser())
	if err != nil {
		stark.Logger.Infof(ctx, "OrgSave-error: %+v", err)
		return response, errcode.CTogRPCError(err)
	}

	response.List = make([]*basePb.MenuListItem, 0)
	for _, item := range menuConfigList {
		menuItem := item.Menu
		permissionList := item.PermissionList
		pbPermissionList := make([]*basePb.PermissionItem, 0)
		if permissionList != nil {
			for _, pItem := range permissionList {
				pbPermissionList = append(pbPermissionList, &basePb.PermissionItem{
					Id:     pItem.Id,
					Name:   pItem.PerName,
					Type:   pItem.PerType,
					MenuId: pItem.GfyxMenuId,
				})
			}
		}
		response.List = append(response.List, &basePb.MenuListItem{
			Id:             menuItem.Id,
			Name:           menuItem.Name,
			ParentId:       menuItem.ParentId,
			Icon:           menuItem.Icon,
			Path:           menuItem.Path,
			Url:            menuItem.Url,
			UrlType:        menuItem.UrlType,
			Sort:           menuItem.Sort,
			Extend:         menuItem.Extend,
			IsLeaf:         menuItem.IsLeaf,
			PermissionList: pbPermissionList,
			IsSelected:     item.IsSelected,
		})
	}

	return response, nil
}
